package com.lottery.ruok.lottrey.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.eventbusObject.ForgetPassword;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.ForgetPasswordRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetCountryRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ForgetPasswordResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetCountryResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import utils.Utils;

public class ForgetPasswordActivity1 extends BaseActivity {
    private String e164String = "86";

    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.flag)
    ImageView flag;
    @BindView(R.id.flag_area)
    LinearLayout flagArea;
    @BindView(R.id.next)
    TextView next;

    private GetCountryResponse getCountryResponse;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);

        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void finishSelf(ForgetPassword forgetPassword){
        finish();
    }

    private void getCountryList(final String code) {
        RetrofitBase.getRetrofit().create(GetCountryRequest.class).getResult()
                .compose(RxHelper.<GetCountryResponse>handleResult())
                .subscribe(new RxSubscribe<GetCountryResponse>(this) {
                    @Override
                    protected void _onNext(GetCountryResponse g) {
                        getCountryResponse = g;

//                        for(GetCountryResponse.ListBean listBean : getCountryResponse.getList()){
////                            listBean.setFisrtLetter(Pinyin.toPinyin(listBean.getCountry(), "").substring(0, 1).toUpperCase());
//                            listBean.setFisrtLetter(listBean.getCountry().substring(0, 1).toUpperCase());
//                        }
                        int index = 0;
                        for(int i = 0; i < getCountryResponse.getList().size(); i++){
                            if(getCountryResponse.getList().get(i).getCode().equals(code)){
                                index = i;
                                break;
                            }
                        }

                        getFlagImage(index);
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    private void getFlagImage(final int index){
        Observable.fromCallable(new Callable<Bitmap>() {
            @Override
            public Bitmap call() {
                try {
                    URL url = new URL(getCountryResponse.getImage());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    InputStream is = conn.getInputStream();
                    return BitmapFactory.decodeStream(is);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        flag.setImageBitmap(Bitmap.createBitmap(bitmap, -Integer.parseInt(getCountryResponse.getList().get(index).getPosition()), 0, getCountryResponse.getList().get(index).getWidth(), 15));
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void init() {
        String phone_code = Utils.GetCountryZipCode(ForgetPasswordActivity1.this);//获取sim卡国际区号
        if(phone_code != null && !phone_code.equals("")){
            e164String = phone_code;
            getCountryList("+" + e164String);
        }

        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(phone.getText().length() == 0){
                    next.setEnabled(false);
                    next.setTextColor(Color.parseColor("#8539d1"));
                } else {
                    next.setEnabled(true);
                    next.setTextColor(Color.parseColor("#ffffff"));
                }
            }
        });
    }

    @OnClick({R.id.flag_area, R.id.next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flag_area:
                Intent intents = new Intent(ForgetPasswordActivity1.this, ChooseE164Activity.class);
                startActivityForResult(intents, 100);
                break;
            case R.id.next:
                //sendAnalyticMsg("lottery_" + LoginActivity.ANALYTIC_VERSION + "_me_setting_forgetpwd_next");

                checkPhoneExist();
                break;
        }
    }

    private void checkPhoneExist(){
        final String phones = e164String +"_"+ phone.getText().toString().replaceFirst("^0*", "");
        RetrofitBase.getRetrofit().create(ForgetPasswordRequest.class)
                .getResult(1, phones, null, null, null)
                .compose(RxHelper.<ForgetPasswordResponse>handleResult())
                .subscribe(new RxSubscribe<ForgetPasswordResponse>(this) {
                    @Override
                    protected void _onNext(ForgetPasswordResponse forgetPasswordResponse) {
                        if(forgetPasswordResponse.getStatus() == 0){
                            Utils.showToast("该手机号未注册");
                        } else {
                            if(forgetPasswordResponse.getWithdraw_password() == 1){
                                Intent intent = new Intent(ForgetPasswordActivity1.this, ForgetPasswordActivity2.class);
                                intent.putExtra("e164String", e164String);
                                intent.putExtra("phone", forgetPasswordResponse.getPhone_number()); // 小韓返回 "e164String_phone" 格式
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(ForgetPasswordActivity1.this, ForgetPasswordActivity3.class);
                                intent.putExtra("e164String", e164String);
                                intent.putExtra("phone", forgetPasswordResponse.getPhone_number()); // 小韓返回 "e164String_phone" 格式
                                startActivity(intent);
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                flag.setImageBitmap(ChooseE164Activity.chooseFlag);

                e164String = data.getStringExtra("e164").replace("+", "");
            }
        }
    }
}
